<?php
/**
 * Created by PhpStorm.
 * User: DELL
 * Date: 2019/3/18
 * Time: 16:20
 */

namespace app\admin\controller;
use app\admin\model\Category as CategoryModel;
use think\Request;
use think\Cache;

class Category extends Common{
    protected $category;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->category=new CategoryModel();
        $this->request = Request::instance();
    }
    //展示所有的类别
    public function index(){
        $data=Cache::get("category");
        if(!$data){
            echo"缓存中没数据";
            $data = $this->category->getTree();
            Cache::set("category",$data);
        }
        $this->assign("categories",$data);
        return $this->fetch();
    }

    //添加更新类别
    public function set(){
        if ($this->request->isGet()) {
            $id = input('id', '');
            if (!empty($id)) {
                //如果用户点击的“编辑”，则查询出待编辑的类别信息
                $row = $this->category->get($id);
                //get方法返回的是一个对象，如果志向获取其中数据，可以使用下面的方法
                //p($row->getData());
                $this->assign('row', $row);
            }else{
                $this->assign('row', '');
            }

            //查询所有的类别
            $data = $this->category->getTree();
            $this->assign('categories', $data);
            return $this->fetch();
        } else {
            $data = $this->request->post();
            /* if (!empty($id)){
                 $model=$this->category->get($id);
             }else{
                 $model=new CategoryModel();
             }*/
            if (!empty($id)){
                $this->category=$this->category->get($id);
            }
            $res=$this->category->data($data)->save();

            if ($res) {
                $this->deleteCache();
                $this->success('设置类别成功', 'index');
            } else {
                $this->error('设置类别失败', 'set');
            }
        }
    }
    public function deleteCache(){
        Cache::rm('category');
    }
}